package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.entity.Notice;
import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.example.springboot.service.ICommentService;
import com.example.springboot.entity.Comment;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgc
 * @since 2023-08-27
 */
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Resource
    private ICommentService commentService;

    //新增和修改
    @PostMapping
    @HoneyLogs(operation = "评论",type = LogType.ADD)
    public Result save(@RequestBody Comment comment) {  //@RequestBody接收前端数据
        if (comment.getId() == null) {
            comment.setUserId(TokenUtils.getCurrentUser().getId());
            comment.setTime(DateUtil.now());

            /**没有pid与 OriginId 就是一级评论， pid也就是你回复用户的评论id, OriginId也就是在一级评论的id*/

            if (comment.getPid() != null) {   // 判断如果回复，进行处理
                Integer pid = comment.getPid();
                Comment pComment = commentService.getById(pid);
                if (pComment.getOriginId() != null) {  // 如果当前回复的父级有祖宗，那么就设置相同的祖宗
                    comment.setOriginId(pComment.getOriginId());
                } else {   // 否则就设置父级为当前回复的祖宗
                    comment.setOriginId(comment.getPid());
                }
            }
        }
        return Result.success(commentService.saveOrUpdate(comment));
    }

    //查询所有数据
    @GetMapping()
    public Result findAll() {
        return Result.success(commentService.list());
    }

    @GetMapping("/tree/{articleId}")
    public Result findTree(@PathVariable Integer articleId) {
//        与user表链接把所有数据查出来
        List<Comment> articleComments = commentService.findCommentDetail(articleId);

        // 把第一层查找出来,查询评论(不包括回复)
        /**没有pid与 OriginId 就是一级评论， pid也就是你回复用户的评论id, OriginId也就是在一级评论的id*/
        List<Comment> originList = articleComments.stream().filter(comment -> comment.getOriginId() == null)
                .collect(Collectors.toList());

//    遍历所有评论内容 ,设置评论数据的子节点，也就是回复内容
        for (Comment origin : originList) {
//            表示回复的对象集合
            List<Comment> comments = articleComments.stream().filter(comment -> origin.getId().
                    equals(comment.getOriginId())).collect(Collectors.toList());


            comments.forEach(comment -> {
                // 找到父级评论的用户id和用户昵称，并设置给当前的回复对象
                Optional<Comment> pComment = articleComments.stream().filter(c1 -> c1.getId().equals(comment.getPid()))
                        .findFirst(); // 找到当前评论的父级

                pComment.ifPresent(v -> {
//                    pUserId 与 pNickname 也就是被回复人的 userid与nickname
                    comment.setPUserId(v.getUserId());
                    comment.setPNickname(v.getNickname());
                });
            });
            origin.setChildren(comments);
        }

        return Result.success(originList);
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(commentService.getById(id));
    }


    //删除
    @HoneyLogs(operation = "评论",type = LogType.DELETE)
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        commentService.removeById(id);
        return Result.success();
    }

    //批量删除
    @HoneyLogs(operation = "评论",type = LogType.BATCH_DELETE)
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        commentService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam String name,
                           @RequestParam String type,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {

        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        return Result.success(commentService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
}



